package com.study.signin_demo2.controller;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.Query;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.study.signin_demo2.entity.User;
import com.study.signin_demo2.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户controller
 * @author whx
 * @date 2022/2/17
 */
@RestController
@RequestMapping("user")
public class UserController {

    @Autowired
    IUserService userService;

    @GetMapping("hello")
    public String hello(){
        return "login";
    }

    /**
     * 登陆方法
     * @param username 用户名
     * @param password 密码
     * @return 检验是否通过
     */
    @PostMapping("login")
    public Boolean login(String username,String password){
        return userService.login(username,password);
    }

    /**
     * 登陆方法 连接数据库
     * @param username 账号
     * @param password 密码
     * @return 是否通过检验
     */
    @PostMapping("loginWithMysql")
    public Boolean loginWithMysql(String username,String password){
        return userService.loginWithMysql(username,password);
    }

    @GetMapping("getUserByUsername")
    public User getUserByUsername(String username){
        return userService.getOne(new QueryWrapper<User>().select("user_name", "password").eq("user_name", username));
    }

    /**
     * 新增或者修改
     * @param user
     * @return
     */
    @PostMapping("save")
    public Boolean saveOrUpdate(User user){
        return userService.saveOrUpdate(user);
    }

    /**
     * 批量删除
     * @param ids
     * @return
     */
    @PostMapping("deleteByIds")
    public Boolean deleteByIds(String ids){
        return userService.removeByIds(Arrays.stream(ids.split(",")).collect(Collectors.toList()));
    }

    /**
     *
     * @param user
     * @return
     */
    @GetMapping("page")
    public IPage<User> page(User user, Page page){
        IPage<User> userPage = new Page<>(page.getCurrent(), page.getSize());
        return userService.page(userPage,Wrappers.lambdaQuery(user));
    }

}
